using System;
using System.Collections.Generic;
using Android.Content;
using Android.Database;
using MuseumsBC.Models;

namespace MuseumsBC.DataAccess
{
    public class MuseumRepository : IMuseumRepository
    {
        private MuseumDatabaseHelper _helper;

        public MuseumRepository(Context context)
        {
            _helper = new MuseumDatabaseHelper(context);
        }

        public IList<Museum> GetAllMuseums()
        {
            ICursor noteCursor = _helper.ReadableDatabase.Query("Note", null, null, null, null, null, null);
            var notes = new List<Museum>();

            while (noteCursor.MoveToNext())
            {
                notes.Add(mapNote(noteCursor));
            }

            return notes;
        }

        // TODO: still don't know diff between museumrepoitory and ormmuseumrepository. created two different "get by id" methods. which one is being called / used? both? don't know
        public Museum GetMuseumById(int museumId)
        {
            ICursor noteCursor = _helper.ReadableDatabase.Query("Museum", null, string.Format("Id = {0}", museumId), null, null, null, null);
            var notes = new List<Museum>();

            while (noteCursor.MoveToNext())
            {
                notes.Add(mapNote(noteCursor));
            }

            return notes.Count == 1 ? notes[0] : null;
        }

        public long AddMuseum(string title, string contents)
        {
            var values = new ContentValues();
            values.Put("Title", title);
            values.Put("Contents", contents);

            return _helper.WritableDatabase.Insert("Note", null, values);
        }

        public long AddMuseum(Museum museum)
        {
            var values = new ContentValues();

            values.Put("Address", museum.Address);
            values.Put("ChinCode", museum.ChinCode);
            values.Put("ChinUrl", museum.ChinUrl);
            values.Put("Contents", museum.Contents);
            values.Put("Description", museum.Description);
            values.Put("HoursOfOperation", museum.HoursOfOperation);
            values.Put("Id", museum.Id);
            values.Put("Image", museum.Image);
            values.Put("Latitude", museum.Latitude);
            values.Put("Longitude", museum.Longitude);
            values.Put("MuseumName", museum.MuseumName);
            values.Put("Telephone", museum.Telephone);
            values.Put("Title", museum.Title);
            values.Put("Web", museum.Web);

            return _helper.WritableDatabase.Insert("Note", null, values);
        }



        private Museum mapNote(ICursor cursor)
        {
            return new Museum
            {
                Id = cursor.GetInt(0),
                Title = cursor.GetString(1),
                Contents = cursor.GetString(2)
            };
        }
    }
}